package com.ylyq.ylxx.service.impl;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ylyq.ylxx.constants.AccountConstant;
import com.ylyq.ylxx.context.FilterContextHandler;
import com.ylyq.ylxx.entity.YlyqAudio;
import com.ylyq.ylxx.entity.YlyqMaterialUrl;
import com.ylyq.ylxx.model.ResponseData;
import com.ylyq.ylxx.model.bean.*;
import com.ylyq.ylxx.model.request.*;
import com.ylyq.ylxx.service.*;
import com.ylyq.ylxx.util.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName OceanengineToolServiceImpl
 * @Description TODO
 * @Author xiaweichao
 * @Date 2020/7/13 11:45
 * @Version 1.0
 */
@Slf4j
@Service
public class OceanengineToolServiceImpl implements IOceanengineToolService {
    @Value("${public.config.fileUploadPath}")
    private String fileUploadPath;
    @Value("${public.config.fileDownloadPath}")
    private String fileDownloadPath;
    @Autowired
    private IFileService fileService;
    @Autowired
    private IYlyqMaterialUrlService iYlyqMaterialUrlService;
    @Autowired
    private IYlyqAudioService iYlyqAudioService;

    @Override
    public ResponseData getActionCategory(ActionCategoryRequest actionCategoryRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "tools/interest_action/action/category/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(actionCategoryRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineActionCategory oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineActionCategory.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData getActionKeyword(ActionKeywordRequest actionCategoryRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "tools/interest_action/action/category/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(actionCategoryRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineActionKeyword oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineActionKeyword.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData getInterestCategory(Long advertiser_id) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "tools/interest_action/interest/category/";

        Map<String, Object> data = new HashMap();
        if (null != advertiser_id)
            data.put("advertiser_id", advertiser_id);

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSONString(data), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineInterestCategory oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineInterestCategory.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public OceanengineInterestKeyword getInterestKeyword(InterestKeywordRequest actionKeywordRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "tools/interest_action/interest/keyword/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(actionKeywordRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineInterestKeyword oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineInterestKeyword.class);
        return oceanengineAccount;
    }

    @Override
    public ResponseData getCustomAudience(CustomAudienceRequest customAudienceRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "dmp/custom_audience/select/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(customAudienceRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineCustomAudience oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineCustomAudience.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData getCustomAudienceDetail(CustomAudienceDetailRequest customAudienceRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "dmp/custom_audience/read/";


        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(customAudienceRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineCustomAudienceDetail oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineCustomAudienceDetail.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData publishCustomAudience(PublishCustomAudienceRequest publishCustomAudienceRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "dmp/custom_audience/publish/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSON(publishCustomAudienceRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanenginePublishCustomAudience oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanenginePublishCustomAudience.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData pushCustomAudience(PushCustomAudienceRequest pushCustomAudienceRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "dmp/custom_audience/push_v2/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSON(pushCustomAudienceRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanenginePushCustomAudience oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanenginePushCustomAudience.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData deleteCustomAudience(DeleteCustomAudienceRequest deleteCustomAudienceRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "dmp/custom_audience/delete/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSON(deleteCustomAudienceRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineDeleteCustomAudience oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineDeleteCustomAudience.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData lookalikeCustomAudience(LookalikeCustomAudienceRequest lookalikeCustomAudienceRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "dmp/custom_audience/lookalike/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSON(lookalikeCustomAudienceRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineLookalikeCustomAudience oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineLookalikeCustomAudience.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData calcCustomAudience(CalcCustomAudienceRequest calcCustomAudienceRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "dmp/custom_audience/calc/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSON(calcCustomAudienceRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineCalcCustomAudience oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineCalcCustomAudience.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData ruleCustomAudience(RuleCustomAudienceRequest ruleCustomAudienceRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "dmp/custom_audience/rule/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSON(ruleCustomAudienceRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineRuleCustomAudience oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineRuleCustomAudience.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData getAudiencePackage(GetAudiencePackageRequest getAudiencePackageRequest) {

        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "audience_package/get/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(getAudiencePackageRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineGetAudiencePackage oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineGetAudiencePackage.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData createAudiencePackage(CreateAudiencePackageRequest createAudiencePackageRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "audience_package/create/";

        Map<String, Object> data = new HashMap();
        if (null != createAudiencePackageRequest.getAdvertiser_id())
            data.put("advertiser_id", createAudiencePackageRequest.getAdvertiser_id());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getName()))
            data.put("name", createAudiencePackageRequest.getName());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getDescription()))
            data.put("description", createAudiencePackageRequest.getDescription());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getLanding_type()))
            data.put("landing_type", createAudiencePackageRequest.getLanding_type());
        if (null != createAudiencePackageRequest.getRetargeting_tags() && createAudiencePackageRequest.getRetargeting_tags().length > 0)
            data.put("retargeting_tags", createAudiencePackageRequest.getRetargeting_tags());
        if (null != createAudiencePackageRequest.getRetargeting_tags_exclude() && createAudiencePackageRequest.getRetargeting_tags_exclude().length > 0)
            data.put("retargeting_tags_exclude", createAudiencePackageRequest.getRetargeting_tags_exclude());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getGender()))
            data.put("gender", createAudiencePackageRequest.getGender());
        if (null != createAudiencePackageRequest.getAge() && createAudiencePackageRequest.getAge().length > 0)
            data.put("age", createAudiencePackageRequest.getAge());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getAndroid_osv()))
            data.put("android_osv", createAudiencePackageRequest.getAndroid_osv());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getIos_osv()))
            data.put("ios_osv", createAudiencePackageRequest.getIos_osv());
        if (null != createAudiencePackageRequest.getCarrier() && createAudiencePackageRequest.getCarrier().length > 0)
            data.put("carrier", createAudiencePackageRequest.getCarrier());
        if (null != createAudiencePackageRequest.getAc() && createAudiencePackageRequest.getAc().length > 0)
            data.put("ac", createAudiencePackageRequest.getAc());
        if (null != createAudiencePackageRequest.getDevice_brand() && createAudiencePackageRequest.getDevice_brand().length > 0)
            data.put("device_brand", createAudiencePackageRequest.getDevice_brand());
        if (null != createAudiencePackageRequest.getArticle_category() && createAudiencePackageRequest.getArticle_category().length > 0)
            data.put("article_category", createAudiencePackageRequest.getArticle_category());
        if (null != createAudiencePackageRequest.getActivate_type() && createAudiencePackageRequest.getActivate_type().length > 0)
            data.put("activate_type", createAudiencePackageRequest.getActivate_type());
        if (null != createAudiencePackageRequest.getPlatform() && createAudiencePackageRequest.getPlatform().length > 0)
            data.put("platform", createAudiencePackageRequest.getPlatform());
        if (null != createAudiencePackageRequest.getAuto_extend_enabled())
            data.put("auto_extend_enabled", createAudiencePackageRequest.getAuto_extend_enabled());
        if (null != createAudiencePackageRequest.getAuto_extend_targets() && createAudiencePackageRequest.getAuto_extend_targets().length > 0)
            data.put("auto_extend_targets", createAudiencePackageRequest.getAuto_extend_targets());
        if (null != createAudiencePackageRequest.getLaunch_price() && createAudiencePackageRequest.getLaunch_price().length > 0)
            data.put("launch_price", createAudiencePackageRequest.getLaunch_price());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getInterest_action_mode()))
            data.put("interest_action_mode", createAudiencePackageRequest.getInterest_action_mode());
        if (null != createAudiencePackageRequest.getAction_scene() && createAudiencePackageRequest.getAction_scene().length > 0)
            data.put("action_scene", createAudiencePackageRequest.getAction_scene());
        if (null != createAudiencePackageRequest.getAction_days())
            data.put("action_days", createAudiencePackageRequest.getAction_days());
        if (null != createAudiencePackageRequest.getAction_categories() && createAudiencePackageRequest.getAction_categories().length > 0)
            data.put("action_categories", createAudiencePackageRequest.getAction_categories());
        if (null != createAudiencePackageRequest.getAction_words() && createAudiencePackageRequest.getAction_words().length > 0)
            data.put("action_words", createAudiencePackageRequest.getAction_words());
        if (null != createAudiencePackageRequest.getInterest_categories() && createAudiencePackageRequest.getInterest_categories().length > 0)
            data.put("interest_categories", createAudiencePackageRequest.getInterest_categories());
        if (null != createAudiencePackageRequest.getInterest_words() && createAudiencePackageRequest.getInterest_words().length > 0)
            data.put("interest_words", createAudiencePackageRequest.getInterest_words());
        if (null != createAudiencePackageRequest.getCity() && createAudiencePackageRequest.getCity().length > 0)
            data.put("city", createAudiencePackageRequest.getCity());
        if (null != createAudiencePackageRequest.getBusiness_ids() && createAudiencePackageRequest.getBusiness_ids().length > 0)
            data.put("business_ids", createAudiencePackageRequest.getBusiness_ids());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getDistrict()))
            data.put("district", createAudiencePackageRequest.getDistrict());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getLocation_type()))
            data.put("location_type", createAudiencePackageRequest.getLocation_type());
        if (null != createAudiencePackageRequest.getAweme_fans_numbers() && createAudiencePackageRequest.getAweme_fans_numbers().length > 0)
            data.put("aweme_fans_numbers", createAudiencePackageRequest.getAweme_fans_numbers());
        if (null != createAudiencePackageRequest.getFilter_aweme_abnormal_active())
            data.put("filter_aweme_abnormal_active", createAudiencePackageRequest.getFilter_aweme_abnormal_active());
        if (null != createAudiencePackageRequest.getFilter_aweme_fans_count())
            data.put("filter_aweme_fans_count", createAudiencePackageRequest.getFilter_aweme_fans_count());
        if (null != createAudiencePackageRequest.getFilter_own_aweme_fans())
            data.put("filter_own_aweme_fans", createAudiencePackageRequest.getFilter_own_aweme_fans());
        if (null != createAudiencePackageRequest.getAweme_fan_accounts() && createAudiencePackageRequest.getAweme_fan_accounts().length > 0)
            data.put("aweme_fan_accounts", createAudiencePackageRequest.getAweme_fan_accounts());
        if (null != createAudiencePackageRequest.getAweme_fan_categories() && createAudiencePackageRequest.getAweme_fan_categories().length > 0)
            data.put("aweme_fan_categories", createAudiencePackageRequest.getAweme_fan_categories());
        if (null != createAudiencePackageRequest.getAweme_fan_behaviors() && createAudiencePackageRequest.getAweme_fan_behaviors().length > 0)
            data.put("aweme_fan_behaviors", createAudiencePackageRequest.getAweme_fan_behaviors());
        if (null != createAudiencePackageRequest.getHide_if_exists())
            data.put("hide_if_exists", createAudiencePackageRequest.getHide_if_exists());


        if (null != createAudiencePackageRequest.getGeolocation() && createAudiencePackageRequest.getGeolocation().length > 0) {

            List<Map<String, Object>> filter = new ArrayList<>();
            for (CreateAudiencePackageRequest.GeolocationRequest temp : createAudiencePackageRequest.getGeolocation()) {
                Map<String, Object> map = new HashMap<>();
                if (StringUtils.isNotBlank(temp.getProvince()))
                    map.put("province", temp.getProvince());
                if (StringUtils.isNotBlank(temp.getCity()))
                    map.put("city", temp.getCity());
                if (StringUtils.isNotBlank(temp.getName()))
                    map.put("name", temp.getName());
                if (null != temp.getLong_())
                    map.put("long", temp.getLong_());
                if (null != temp.getLat())
                    map.put("lat", temp.getLat());
                if (StringUtils.isNotBlank(temp.getStreet()))
                    map.put("street", temp.getStreet());
                if (StringUtils.isNotBlank(temp.getDistrict()))
                    map.put("district", temp.getDistrict());
                if (null != temp.getRadius())
                    map.put("radius", temp.getRadius());
                if (StringUtils.isNotBlank(temp.getStreet_number()))
                    map.put("street_number", temp.getStreet_number());

                if (map.size() > 0)
                    filter.add(map);
            }

            if (filter.size() > 0)
                data.put("geolocation", filter);
        }

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSONString(data), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineCreateAudiencePackage oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineCreateAudiencePackage.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData updateAudiencePackage(UpdateAudiencePackageRequest createAudiencePackageRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "audience_package/create/";

        Map<String, Object> data = new HashMap();
        if (null != createAudiencePackageRequest.getAdvertiser_id())
            data.put("advertiser_id", createAudiencePackageRequest.getAdvertiser_id());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getName()))
            data.put("name", createAudiencePackageRequest.getName());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getDescription()))
            data.put("description", createAudiencePackageRequest.getDescription());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getAudience_package_id()))
            data.put("audience_package_id", createAudiencePackageRequest.getAudience_package_id());
        if (null != createAudiencePackageRequest.getRetargeting_tags() && createAudiencePackageRequest.getRetargeting_tags().length > 0)
            data.put("retargeting_tags", createAudiencePackageRequest.getRetargeting_tags());
        if (null != createAudiencePackageRequest.getRetargeting_tags_exclude() && createAudiencePackageRequest.getRetargeting_tags_exclude().length > 0)
            data.put("retargeting_tags_exclude", createAudiencePackageRequest.getRetargeting_tags_exclude());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getGender()))
            data.put("gender", createAudiencePackageRequest.getGender());
        if (null != createAudiencePackageRequest.getAge() && createAudiencePackageRequest.getAge().length > 0)
            data.put("age", createAudiencePackageRequest.getAge());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getAndroid_osv()))
            data.put("android_osv", createAudiencePackageRequest.getAndroid_osv());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getIos_osv()))
            data.put("ios_osv", createAudiencePackageRequest.getIos_osv());
        if (null != createAudiencePackageRequest.getCarrier() && createAudiencePackageRequest.getCarrier().length > 0)
            data.put("carrier", createAudiencePackageRequest.getCarrier());
        if (null != createAudiencePackageRequest.getAc() && createAudiencePackageRequest.getAc().length > 0)
            data.put("ac", createAudiencePackageRequest.getAc());
        if (null != createAudiencePackageRequest.getDevice_brand() && createAudiencePackageRequest.getDevice_brand().length > 0)
            data.put("device_brand", createAudiencePackageRequest.getDevice_brand());
        if (null != createAudiencePackageRequest.getArticle_category() && createAudiencePackageRequest.getArticle_category().length > 0)
            data.put("article_category", createAudiencePackageRequest.getArticle_category());
        if (null != createAudiencePackageRequest.getActivate_type() && createAudiencePackageRequest.getActivate_type().length > 0)
            data.put("activate_type", createAudiencePackageRequest.getActivate_type());
        if (null != createAudiencePackageRequest.getPlatform() && createAudiencePackageRequest.getPlatform().length > 0)
            data.put("platform", createAudiencePackageRequest.getPlatform());
        if (null != createAudiencePackageRequest.getAuto_extend_enabled())
            data.put("auto_extend_enabled", createAudiencePackageRequest.getAuto_extend_enabled());
        if (null != createAudiencePackageRequest.getAuto_extend_targets() && createAudiencePackageRequest.getAuto_extend_targets().length > 0)
            data.put("auto_extend_targets", createAudiencePackageRequest.getAuto_extend_targets());
        if (null != createAudiencePackageRequest.getLaunch_price() && createAudiencePackageRequest.getLaunch_price().length > 0)
            data.put("launch_price", createAudiencePackageRequest.getLaunch_price());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getInterest_action_mode()))
            data.put("interest_action_mode", createAudiencePackageRequest.getInterest_action_mode());
        if (null != createAudiencePackageRequest.getAction_scene() && createAudiencePackageRequest.getAction_scene().length > 0)
            data.put("action_scene", createAudiencePackageRequest.getAction_scene());
        if (null != createAudiencePackageRequest.getAction_days())
            data.put("action_days", createAudiencePackageRequest.getAction_days());
        if (null != createAudiencePackageRequest.getAction_categories() && createAudiencePackageRequest.getAction_categories().length > 0)
            data.put("action_categories", createAudiencePackageRequest.getAction_categories());
        if (null != createAudiencePackageRequest.getAction_words() && createAudiencePackageRequest.getAction_words().length > 0)
            data.put("action_words", createAudiencePackageRequest.getAction_words());
        if (null != createAudiencePackageRequest.getInterest_categories() && createAudiencePackageRequest.getInterest_categories().length > 0)
            data.put("interest_categories", createAudiencePackageRequest.getInterest_categories());
        if (null != createAudiencePackageRequest.getInterest_words() && createAudiencePackageRequest.getInterest_words().length > 0)
            data.put("interest_words", createAudiencePackageRequest.getInterest_words());
        if (null != createAudiencePackageRequest.getCity() && createAudiencePackageRequest.getCity().length > 0)
            data.put("city", createAudiencePackageRequest.getCity());
        if (null != createAudiencePackageRequest.getBusiness_ids() && createAudiencePackageRequest.getBusiness_ids().length > 0)
            data.put("business_ids", createAudiencePackageRequest.getBusiness_ids());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getDistrict()))
            data.put("district", createAudiencePackageRequest.getDistrict());
        if (StringUtils.isNotBlank(createAudiencePackageRequest.getLocation_type()))
            data.put("location_type", createAudiencePackageRequest.getLocation_type());
        if (null != createAudiencePackageRequest.getAweme_fans_numbers() && createAudiencePackageRequest.getAweme_fans_numbers().length > 0)
            data.put("aweme_fans_numbers", createAudiencePackageRequest.getAweme_fans_numbers());
        if (null != createAudiencePackageRequest.getFilter_aweme_abnormal_active())
            data.put("filter_aweme_abnormal_active", createAudiencePackageRequest.getFilter_aweme_abnormal_active());
        if (null != createAudiencePackageRequest.getFilter_aweme_fans_count())
            data.put("filter_aweme_fans_count", createAudiencePackageRequest.getFilter_aweme_fans_count());
        if (null != createAudiencePackageRequest.getFilter_own_aweme_fans())
            data.put("filter_own_aweme_fans", createAudiencePackageRequest.getFilter_own_aweme_fans());
        if (null != createAudiencePackageRequest.getAweme_fan_accounts() && createAudiencePackageRequest.getAweme_fan_accounts().length > 0)
            data.put("aweme_fan_accounts", createAudiencePackageRequest.getAweme_fan_accounts());
        if (null != createAudiencePackageRequest.getAweme_fan_categories() && createAudiencePackageRequest.getAweme_fan_categories().length > 0)
            data.put("aweme_fan_categories", createAudiencePackageRequest.getAweme_fan_categories());
        if (null != createAudiencePackageRequest.getAweme_fan_behaviors() && createAudiencePackageRequest.getAweme_fan_behaviors().length > 0)
            data.put("aweme_fan_behaviors", createAudiencePackageRequest.getAweme_fan_behaviors());
        if (null != createAudiencePackageRequest.getHide_if_exists())
            data.put("hide_if_exists", createAudiencePackageRequest.getHide_if_exists());


        if (null != createAudiencePackageRequest.getGeolocation() && createAudiencePackageRequest.getGeolocation().length > 0) {

            List<Map<String, Object>> filter = new ArrayList<>();
            for (UpdateAudiencePackageRequest.GeolocationRequest temp : createAudiencePackageRequest.getGeolocation()) {
                Map<String, Object> map = new HashMap<>();
                if (StringUtils.isNotBlank(temp.getProvince()))
                    map.put("province", temp.getProvince());
                if (StringUtils.isNotBlank(temp.getCity()))
                    map.put("city", temp.getCity());
                if (StringUtils.isNotBlank(temp.getName()))
                    map.put("name", temp.getName());
                if (null != temp.getLong_())
                    map.put("long", temp.getLong_());
                if (null != temp.getLat())
                    map.put("lat", temp.getLat());
                if (StringUtils.isNotBlank(temp.getStreet()))
                    map.put("street", temp.getStreet());
                if (StringUtils.isNotBlank(temp.getDistrict()))
                    map.put("district", temp.getDistrict());
                if (null != temp.getRadius())
                    map.put("radius", temp.getRadius());
                if (StringUtils.isNotBlank(temp.getStreet_number()))
                    map.put("street_number", temp.getStreet_number());

                if (map.size() > 0)
                    filter.add(map);
            }

            if (filter.size() > 0)
                data.put("geolocation", filter);
        }

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSONString(data), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineUpdateAudiencePackage oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUpdateAudiencePackage.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData deleteAudiencePackage(DeleteAudiencePackageRequest deleteAudiencePackageRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "audience_package/delete/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSON(deleteAudiencePackageRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineUpdateAudiencePackage oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUpdateAudiencePackage.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData bindAudiencePackage(BindAudiencePackageRequest bindAudiencePackageRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "audience_package/ad/bind/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSON(bindAudiencePackageRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineBindAudiencePackage oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineBindAudiencePackage.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public ResponseData unbindAudiencePackage(UnBindAudiencePackageRequest bindAudiencePackageRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "audience_package/ad/unbind/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSON(bindAudiencePackageRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineUnBindAudiencePackage oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUnBindAudiencePackage.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public OceanengineGetIndustry getIndustry(GetIndustryPackageRequest getIndustryPackageRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "tools/industry/get/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(getIndustryPackageRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineGetIndustry oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineGetIndustry.class);
        if (null != oceanengineAccount.getData() && !oceanengineAccount.getData().getList().isEmpty()) {

            List<OceanengineGetIndustry.DataBean.OceanengineGetIndustryListBean> resultList = new ArrayList<>();
            List<OceanengineGetIndustry.DataBean.OceanengineGetIndustryListBean> list = oceanengineAccount.getData().getList();
            for (OceanengineGetIndustry.DataBean.OceanengineGetIndustryListBean temp : list) {//获取第一级
                if (temp.getLevel() == 1) {
                    resultList.add(temp);
                }
            }
            for (OceanengineGetIndustry.DataBean.OceanengineGetIndustryListBean temp : list) {//获取第二级
                if (temp.getLevel() == 2) {
                    for (OceanengineGetIndustry.DataBean.OceanengineGetIndustryListBean first : resultList) {
                        if (temp.getFirst_industry_id().longValue() == first.getIndustry_id().longValue()) {
                            if (first.getChildren() == null) {
                                first.setChildren(new ArrayList<>());
                            }
                            first.getChildren().add(temp);
                            break;
                        }
                    }
                }
            }
            for (OceanengineGetIndustry.DataBean.OceanengineGetIndustryListBean temp : list) {//获取第三级
                if (temp.getLevel() == 3) {
                    for (OceanengineGetIndustry.DataBean.OceanengineGetIndustryListBean first : resultList) {
                        for (OceanengineGetIndustry.DataBean.OceanengineGetIndustryListBean second : first.getChildren()) {
                            if (temp.getSecond_industry_id().longValue() == second.getIndustry_id().longValue()) {
                                if (second.getChildren() == null) {
                                    second.setChildren(new ArrayList<>());
                                }
                                second.getChildren().add(temp);
                                break;
                            }
                        }
//                        break;
                    }
                }
            }


//            int size = list.size();
//            for (int i = size - 1; i > -1; i--) {
//                switch (getIndustryPackageRequest.getLevel()) {
//                    case 2:
//                        if (list.get(i).getFirst_industry_id() == getIndustryPackageRequest.getParentID()) {
//                            list.remove(i);
//                        }
//                        break;
//                    case 3:
//                        if (list.get(i).getSecond_industry_id() == getIndustryPackageRequest.getParentID()) {
//                            list.remove(i);
//                        }
//                        break;
//                }
//            }
//            oceanengineAccount.getData().setList(list);
            oceanengineAccount.getData().setList(resultList);
        }
        return oceanengineAccount;
    }

    @Override
    public ResponseData getProceduralPackage(GetProceduralPackageRequest getIndustryPackageRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "tools/procedural_package/get/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(getIndustryPackageRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineGetProceduralPackage oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineGetProceduralPackage.class);
        return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
    }

    @Override
    public OceanengineEstimateAudience estimateAudience(EstimateAudienceRequest estimateAudienceRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "tools/estimate_audience/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());
        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(estimateAudienceRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineEstimateAudience oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineEstimateAudience.class);
        return oceanengineAccount;
    }

    @Override
    public OceanengineSuggestBid suggestBid(SuggestBidRequest suggestBidRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "tools/bid/suggest/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());
        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(suggestBidRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineSuggestBid oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineSuggestBid.class);
        return oceanengineAccount;
    }

    @Override
    public OceanengineAdStatExtraInfo ad_stat_extra_info(AdStatExtraInfoRequest suggestBidRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "tools/ad_stat_extra_info/get/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());
        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(suggestBidRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineAdStatExtraInfo oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineAdStatExtraInfo.class);
        return oceanengineAccount;
    }

    @Override
    public OceanengineCreativeWord getCreativeWord(CreativeWordRequest creativeWordRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "tools/creative_word/select/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());
        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(creativeWordRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineCreativeWord oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineCreativeWord.class);
        return oceanengineAccount;
    }

    @Override
    public ResponseData uploadFileImage(UploadFileImageRequest uploadFileImageRequest) {

        OkHttpClient client = new OkHttpClient();
        Response response = null;
        try {
            // 由于浏览器安全限制，无法获取您刚才选择的完整路径,请在代码中作出相应的修改

            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("upload_type", uploadFileImageRequest.getUpload_type())
                    .addFormDataPart("advertiser_id", String.valueOf(uploadFileImageRequest.getAdvertiser_id()))
                    .addFormDataPart("filename", StringUtils.isNotBlank(uploadFileImageRequest.getFilename()) ? uploadFileImageRequest.getFilename() : Tools.getUUID());
            String fileUrl = null;
            if (uploadFileImageRequest.getUpload_type().equals("UPLOAD_BY_FILE")) {
                try {
                    if (null != uploadFileImageRequest.getImage_file())
                        fileUrl = fileService.uploadPhotoOrFile(uploadFileImageRequest.getImage_file());
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                if (StringUtils.isNotBlank(fileUrl)) {
                    // 获取文件名，带后缀
                    String originalFilename = uploadFileImageRequest.getImage_file().getOriginalFilename();
                    // 获取文件的后缀格式
                    String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
                    File fileimage_file = new File(fileUrl.replace(fileDownloadPath, fileUploadPath));
//                    String fileMD5String2 = MD5Utils.getMD5(fileimage_file);
                    builder.addFormDataPart("image_file", originalFilename, RequestBody.create(MediaType.parse("image/" + fileSuffix), fileimage_file))
                            .addFormDataPart("image_signature", uploadFileImageRequest.getImage_signature());
                } else {
                    return new ResponseData(ResponseData.Result.FAIL);
                }
            } else if (uploadFileImageRequest.getUpload_type().equals("UPLOAD_BY_URL")) {
                builder.addFormDataPart("image_url", uploadFileImageRequest.getImage_url());
            }
            RequestBody requestBody = builder.build();


            Request request = new Request.Builder()
                    .url("https://ad.oceanengine.com/open_api/2/file/image/ad/")
                    .header("Access-Token", FilterContextHandler.getOceaneToken())
//                    .header("Access-Token", FilterContextHandler.getOceaneToken())
                    .post(requestBody)
                    .build();

            response = client.newCall(request).execute();
            String result = response.body().string();
            log.info(result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            OceanengineUploadFileImage oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUploadFileImage.class);
            if (oceanengineAccount.getCode() == AccountConstant.SUCCESS) {
                YlyqMaterialUrl ylyqMaterialUrl = new YlyqMaterialUrl();
                ylyqMaterialUrl.setUrl(StringUtils.isBlank(fileUrl) ? uploadFileImageRequest.getImage_url() : fileUrl);
                ylyqMaterialUrl.setMaterialId(oceanengineAccount.getData().getId());
                iYlyqMaterialUrlService.save(ylyqMaterialUrl);
            }
            return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
//                return JSONObject.parseObject(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null)
                response.close();
        }
        return new ResponseData(ResponseData.Result.FAIL);
    }

    @Override
    public ResponseData uploadFileVideo(UploadFileVideoRequest uploadFileVideoRequest) {

        OkHttpClient client = new OkHttpClient();
        Response response = null;
        try {

            // 获取文件名，带后缀
            String originalFilename = uploadFileVideoRequest.getVideo_file().getOriginalFilename();
            // 获取文件的后缀格式
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();

            String fileUrl = null;
            try {
                if (null != uploadFileVideoRequest.getVideo_file())
                    fileUrl = fileService.uploadPhotoOrFile(uploadFileVideoRequest.getVideo_file());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            // 由于浏览器安全限制，无法获取您刚才选择的完整路径,请在代码中作出相应的修改
            File filevideo_file = new File(fileUrl.replace(fileDownloadPath, fileUploadPath));
//            String fileMD5String2 = MD5Utils.getMD5(filevideo_file);
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("advertiser_id", String.valueOf(uploadFileVideoRequest.getAdvertiser_id()))
                    .addFormDataPart("video_file", originalFilename, RequestBody.create(MediaType.parse("video/" + fileSuffix), filevideo_file))
                    .addFormDataPart("video_signature", uploadFileVideoRequest.getVideo_signature())
                    .addFormDataPart("filename", StringUtils.isNotBlank(uploadFileVideoRequest.getFilename()) ? uploadFileVideoRequest.getFilename() : originalFilename)
                    .build();

            Request request = new Request.Builder()
                    .url("https://ad.oceanengine.com/open_api/2/file/video/ad/")
                    .header("Access-Token", FilterContextHandler.getOceaneToken())
                    .post(requestBody)
                    .build();

            response = client.newCall(request).execute();
            String result = response.body().string();
            log.info(result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            OceanengineUploadFileVideo oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUploadFileVideo.class);
            if (oceanengineAccount.getCode() == AccountConstant.SUCCESS) {
                YlyqMaterialUrl ylyqMaterialUrl = new YlyqMaterialUrl();
                ylyqMaterialUrl.setUrl(fileUrl);
                ylyqMaterialUrl.setMaterialId(oceanengineAccount.getData().getVideo_id());
                iYlyqMaterialUrlService.save(ylyqMaterialUrl);
            }
            return new ResponseData(ResponseData.Result.SUCCESS, oceanengineAccount);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null)
                response.close();
        }
        return null;
    }

    //另一种的上传视频方式
    public String uploadAdvideo(String advertiser, String signature, String mergeVideoPath) {

        // 请求地址
        String open_api_url_prefix = "https://ad.oceanengine.com/open_api/2/";
        String uri = "file/video/ad/";

        // 构造请求
        HttpPost httpPost = new HttpPost(open_api_url_prefix + uri);
        httpPost.setHeader("Access-Token", FilterContextHandler.getOceaneToken());

        // 文件参数
        FileBody file = new FileBody(new File(mergeVideoPath));
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create()
                .addPart("video_file", file);

        // 其他参数
        entityBuilder.addTextBody("advertiser_id", advertiser);
        entityBuilder.addTextBody("video_signature", signature);
        HttpEntity entity = entityBuilder.build();

        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;

        try {
            client = HttpClientBuilder.create().build();
            httpPost.setURI(URI.create(open_api_url_prefix + uri));

            httpPost.setEntity(entity);

            response = client.execute(httpPost);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer result = new StringBuffer();
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    result.append(line);
                }
                bufferedReader.close();
                return result.toString();
            } else if (response == null)
                return null;
            else
                return response.toString();

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    //另一种的上传视频方式
    public void uploadAdvideo1(String advertiser, String signature, String mergeVideoPath) {
        //            OkHttpClient client = new OkHttpClient();
//            Response response = null;
//            //文件上传
//            File filevideo_file = new File(mergeVideoPath);
//            RequestBody requestBody = new MultipartBody.Builder()
//                    .setType(MultipartBody.FORM)
//                    .addFormDataPart("advertiser_id", String.valueOf(advertiser_id))
//                    .addFormDataPart("video_file", newFileName, RequestBody.create(MediaType.parse("video/" + fileSuffix), filevideo_file))
//                    .addFormDataPart("video_signature", MD5Utils.getMD5(filevideo_file))
//                    .addFormDataPart("filename", newFileName)
//                    .build();
//            log.info("start4");
//            Request request = new Request.Builder()
//                    .url("https://ad.oceanengine.com/open_api/2/file/video/ad/")
//                    .header("Access-Token", FilterContextHandler.getOceaneToken())
//                    .post(requestBody)
//                    .build();
//
//            response = client.newCall(request).execute();
//            String result = response.body().string();
//
////            String result=uploadAdvideo(String.valueOf(advertiser_id),MD5Utils.getMD5(filevideo_file),mergeVideoPath).toJSONString();
//            log.info(result);
    }

    @Override
    public ResponseData uploadFileScrapVideo(Long advertiser_id, MultipartFile[] files1, MultipartFile[] files2, MultipartFile[] files3, MultipartFile[] files4, MultipartFile[] files5) {
        try {
            log.info("start1");
            List<OceanengineUploadFileVideo> oceanengineUploadFileVideoList = new ArrayList<>();
            if (files1 == null || files1.length == 0 || files2 == null || files2.length == 0 || files3 == null || files3.length == 0 || files4 == null || files4.length == 0 || files5 == null || files5.length == 0)
                return new ResponseData(ResponseData.Result.FAIL);
            List<String> videos1 = new ArrayList<>();
            List<String> videos2 = new ArrayList<>();
            List<String> videos3 = new ArrayList<>();
            List<String> videos4 = new ArrayList<>();
            List<String> videos5 = new ArrayList<>();

            for (MultipartFile file1 : files1) {
                videos1.add(fileService.uploadPhotoOrFile(file1).replace(fileDownloadPath, fileUploadPath));
            }
            for (MultipartFile file2 : files2) {
                videos2.add(fileService.uploadPhotoOrFile(file2).replace(fileDownloadPath, fileUploadPath));
            }
            for (MultipartFile file3 : files3) {
                videos3.add(fileService.uploadPhotoOrFile(file3).replace(fileDownloadPath, fileUploadPath));
            }
            for (MultipartFile file4 : files4) {
                videos4.add(fileService.uploadPhotoOrFile(file4).replace(fileDownloadPath, fileUploadPath));
            }
            for (MultipartFile file5 : files5) {
                videos5.add(fileService.uploadPhotoOrFile(file5).replace(fileDownloadPath, fileUploadPath));
            }
            log.info("start2");

            List<List<String>> mergeVideoList = new ArrayList<>();

            for (String video1 : videos1) {
                for (String video2 : videos2) {
                    for (String video3 : videos3) {
                        for (String video4 : videos4) {
                            for (String video5 : videos5) {
                                List<String> mergeVideos = new ArrayList<>();
                                mergeVideos.add(video1);
                                mergeVideos.add(video2);
                                mergeVideos.add(video3);
                                mergeVideos.add(video4);
                                mergeVideos.add(video5);

                                mergeVideoList.add(mergeVideos);

                                log.info("start5");
                            }
                        }
                    }
                }
            }
//用线程池执行，加快效率
            Map<String, Object> allFilterContextHandler = FilterContextHandler.getAll();
            CountDownLatch cdl = new CountDownLatch(mergeVideoList.size());
            ExecutorService fixedThreadPool = Executors.newFixedThreadPool(mergeVideoList.size() > 10 ? 10 : mergeVideoList.size());
            for (int i = 0; i < mergeVideoList.size(); i++) {
                log.info("第" + i + "个开始");
                int finalI = i;
                fixedThreadPool.execute(new Runnable() {
                    public void run() {
                        try {
                            FilterContextHandler.setAll(allFilterContextHandler);
                            // 获取文件名，带后缀
                            String originalFilename = files1[0].getOriginalFilename();
                            // 获取文件的后缀格式
//                                String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
                            // 重新赋名，防止出现名称重复的情况
                            String newFileName = SnowflakeIdWorkerUtil.generateId() + originalFilename;
//文件拼接合并
                            String targetPath = fileUploadPath + "mergeVideo/" + newFileName;

//                                String mergeVideoPath = FfmpegUtil.mergeVideo(mergeVideos, targetPath);
                            String mergeVideoPath = Mp4ParserUtils.mergeVideo(mergeVideoList.get(finalI), targetPath);

                            if (StringUtils.isBlank(mergeVideoPath)) {
                                log.error(mergeVideoPath + "is empty");
                                cdl.countDown();
                                return;
                            }

                            //文件上传
                            File filevideo_file = new File(mergeVideoPath);
                            if (!filevideo_file.exists()) {
                                log.error(mergeVideoPath + "file is not exists");
                                cdl.countDown();
                                return;
                            }
                            log.info("advertiser_id===" + advertiser_id + mergeVideoPath);
                            String result = uploadAdvideo(String.valueOf(advertiser_id), MD5Utils.getMD5(filevideo_file), mergeVideoPath);
                            if (StringUtils.isBlank(result)) {
                                log.error("result is null===" + advertiser_id + mergeVideoPath);
                                cdl.countDown();
                                return;
                            }
                            log.info(result);
                            JSONObject jsonObject = JSONObject.parseObject(result);
                            OceanengineUploadFileVideo oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUploadFileVideo.class);
                            if (oceanengineAccount.getCode() == AccountConstant.SUCCESS) {
                                YlyqMaterialUrl ylyqMaterialUrl = new YlyqMaterialUrl();
                                ylyqMaterialUrl.setUrl(targetPath.replace(fileUploadPath, fileDownloadPath));
                                ylyqMaterialUrl.setMaterialId(oceanengineAccount.getData().getVideo_id());
                                iYlyqMaterialUrlService.save(ylyqMaterialUrl);

                                oceanengineUploadFileVideoList.add(oceanengineAccount);
                                log.info(finalI + "========success");
                            } else {
                                log.error(result);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        cdl.countDown();
                    }
                });
            }

            fixedThreadPool.shutdown();
            cdl.await();

            log.info("start6");
            return new ResponseData(ResponseData.Result.SUCCESS, oceanengineUploadFileVideoList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseData(ResponseData.Result.FAIL);
    }

    public ResponseData uploadFileScrapVideoWithAudio(Long advertiser_id, Long count, MultipartFile[] files1, MultipartFile[] files2, MultipartFile[] files3, MultipartFile[] files4, MultipartFile[] files5) {
        try {
            log.info("start1");
            if (count == null) {
                count = 3l;
            }
            List<OceanengineUploadFileVideo> oceanengineUploadFileVideoList = new ArrayList<>();
            if (files1 == null || files1.length == 0 || files2 == null || files2.length == 0 || files3 == null || files3.length == 0 || files4 == null || files4.length == 0 || files5 == null || files5.length == 0)
                return new ResponseData(ResponseData.Result.FAIL);
            List<String> videos1 = new ArrayList<>();
            List<String> videos2 = new ArrayList<>();
            List<String> videos3 = new ArrayList<>();
            List<String> videos4 = new ArrayList<>();
            List<String> videos5 = new ArrayList<>();

            for (MultipartFile file1 : files1) {
                videos1.add(fileService.uploadPhotoOrFile(file1).replace(fileDownloadPath, fileUploadPath));
            }
            for (MultipartFile file2 : files2) {
                videos2.add(fileService.uploadPhotoOrFile(file2).replace(fileDownloadPath, fileUploadPath));
            }
            for (MultipartFile file3 : files3) {
                videos3.add(fileService.uploadPhotoOrFile(file3).replace(fileDownloadPath, fileUploadPath));
            }
            for (MultipartFile file4 : files4) {
                videos4.add(fileService.uploadPhotoOrFile(file4).replace(fileDownloadPath, fileUploadPath));
            }
            for (MultipartFile file5 : files5) {
                videos5.add(fileService.uploadPhotoOrFile(file5).replace(fileDownloadPath, fileUploadPath));
            }
            log.info("start2");

            List<List<String>> mergeVideoList = new ArrayList<>();

            for (String video1 : videos1) {
                for (String video2 : videos2) {
                    for (String video3 : videos3) {
                        for (String video4 : videos4) {
                            for (String video5 : videos5) {
                                List<String> mergeVideos = new ArrayList<>();
                                mergeVideos.add(video1);
                                mergeVideos.add(video2);
                                mergeVideos.add(video3);
                                mergeVideos.add(video4);
                                mergeVideos.add(video5);

                                mergeVideoList.add(mergeVideos);

                                log.info("start5");
                            }
                        }
                    }
                }
            }

            //用线程池执行，加快效率,拼接视频
            Map<String, Object> allFilterContextHandler = FilterContextHandler.getAll();
            ExecutorService fixedThreadPool = Executors.newFixedThreadPool(mergeVideoList.size() > 7 ? 7 : mergeVideoList.size());
//            ExecutorService fixedThreadPool = Executors.newFixedThreadPool(8);
            CountDownLatch cdl = new CountDownLatch(mergeVideoList.size());
            Vector<String> mergeVideoPathList = new Vector<>();
            //合并碎片视频
            for (int i = 0; i < mergeVideoList.size(); i++) {
                log.info("第" + i + "个开始");
                int finalI = i;
                fixedThreadPool.execute(new Runnable() {
                    public void run() {
                        try {
                            // 获取文件名，带后缀
                            String originalFilename = files1[0].getOriginalFilename();
                            // 获取文件的后缀格式
//                                String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
                            // 重新赋名，防止出现名称重复的情况
                            String newFileName = SnowflakeIdWorkerUtil.generateId() + originalFilename;
//文件拼接合并
                            String targetPath = fileUploadPath + "mergeVideo/" + newFileName;

//                                String mergeVideoPath = FfmpegUtil.mergeVideo(mergeVideos, targetPath);
                            String mergeVideo = Mp4ParserUtils.mergeVideo(mergeVideoList.get(finalI), targetPath);
                            if (StringUtils.isNotBlank(mergeVideo)) {
                                mergeVideoPathList.add(mergeVideo);
                            }
//                        FfmpegUtil.mergeVideoAndAudio(mergeVideoPath,)

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        cdl.countDown();
                    }
                });
            }
            cdl.await();

            //合并音频+视频
            Vector<String> mergeVideoAndAudioList = new Vector<>();
            List<YlyqAudio> audioList = iYlyqAudioService.list();//音频

            if (audioList != null && !audioList.isEmpty()) {

//            视频总数=（计划条数*3>45?计划条数*3：45）
//            取音乐背景的个数=（视频总数/排列组合的视频个数）+1
                long videoCount = count * 3 > 45 ? count * 3 : 45;
                int audioCount = (int) (videoCount / mergeVideoPathList.size() + 1);
                if (audioList.size() > audioCount)
                    audioList = audioList.subList(0, audioCount);

                CountDownLatch cdlVideoWithAudio = new CountDownLatch(mergeVideoPathList.size() * audioList.size());

                for (YlyqAudio ylyqAudio : audioList) {
                    for (String mergeVideoPath : mergeVideoPathList) {
                        fixedThreadPool.execute(new Runnable() {
                            public void run() {
                                try {
                                    // 获取文件名，带后缀
//                        String originalFilename = files1[0].getOriginalFilename();
                                    // 获取文件的后缀格式
//                        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
                                    String fileSuffix = mergeVideoPath.substring(mergeVideoPath.lastIndexOf(".")).toLowerCase();
                                    // 重新赋名，防止出现名称重复的情况
                                    String newFileName = SnowflakeIdWorkerUtil.generateId() + fileSuffix;
//文件拼接合并
                                    String targetPath = fileUploadPath + "mergeVideoWithAudio/" + newFileName;
                                    String mergeVideoAndAudio = FfmpegUtil.mergeVideoAndAudio(mergeVideoPath, ylyqAudio.getAudioUrl(), targetPath);
                                    if (StringUtils.isNotBlank(mergeVideoAndAudio)) {
                                        mergeVideoAndAudioList.add(mergeVideoAndAudio);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                cdlVideoWithAudio.countDown();
                            }
                        });
                    }
                }
                cdlVideoWithAudio.await();
            }
            log.info("合成视频的个数为=======" + mergeVideoAndAudioList.size());
            //上传视频
            if (mergeVideoAndAudioList.isEmpty()) {
                CountDownLatch upload = new CountDownLatch(mergeVideoPathList.size());
                for (String mergeVideoPath : mergeVideoPathList) {
                    fixedThreadPool.execute(new Runnable() {
                        public void run() {
                            try {
                                FilterContextHandler.setAll(allFilterContextHandler);
                                //文件上传
                                File filevideo_file = new File(mergeVideoPath);
                                if (!filevideo_file.exists()) {
                                    log.error(mergeVideoPath + "file is not exists");
                                    filevideo_file.mkdir();
                                    upload.countDown();
                                    return;
                                }
                                log.info("advertiser_id===" + advertiser_id + mergeVideoPath);
                                String md5 = MD5Utils.getMD5(filevideo_file);
                                String result = uploadAdvideo(String.valueOf(advertiser_id), md5, mergeVideoPath);
                                if (StringUtils.isBlank(result)) {
                                    log.error("result is null===" + advertiser_id + mergeVideoPath);
                                    upload.countDown();
                                    return;
                                }
                                log.info(result);

                                JSONObject jsonObject = null;
                                //上传失败重试
                                try {
                                    jsonObject = JSONObject.parseObject(result);
                                } catch (Exception exception) {
                                    result = uploadAdvideo(String.valueOf(advertiser_id), md5, mergeVideoPath);
                                    if (StringUtils.isBlank(result)) {
                                        log.error("result is null===" + advertiser_id + mergeVideoPath);
                                        upload.countDown();
                                        return;
                                    }
                                    jsonObject = JSONObject.parseObject(result);
                                }

                                OceanengineUploadFileVideo oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUploadFileVideo.class);
                                if (oceanengineAccount.getCode() == AccountConstant.SUCCESS) {
                                    YlyqMaterialUrl ylyqMaterialUrl = new YlyqMaterialUrl();
                                    ylyqMaterialUrl.setUrl(mergeVideoPath.replace(fileUploadPath, fileDownloadPath));
                                    ylyqMaterialUrl.setMaterialId(oceanengineAccount.getData().getVideo_id());
                                    iYlyqMaterialUrlService.save(ylyqMaterialUrl);
                                    oceanengineUploadFileVideoList.add(oceanengineAccount);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            upload.countDown();
                        }
                    });

                }
                upload.await();
            } else {
                CountDownLatch upload = new CountDownLatch(mergeVideoAndAudioList.size());
                for (String mergeVideoPath : mergeVideoAndAudioList) {
                    fixedThreadPool.execute(new Runnable() {
                        public void run() {
                            try {
                                FilterContextHandler.setAll(allFilterContextHandler);
                                //文件上传
                                File filevideo_file = new File(mergeVideoPath);
                                if (!filevideo_file.exists()) {
                                    filevideo_file.mkdir();
                                    log.error(mergeVideoPath + "file is not exists");
                                    upload.countDown();
                                    return;
                                }
                                String md5 = MD5Utils.getMD5(filevideo_file);
                                log.info("advertiser_id===" + advertiser_id + ",,md5===" + md5 + ",,mergeVideoPath===" + mergeVideoPath);
                                String result = uploadAdvideo(String.valueOf(advertiser_id), md5, mergeVideoPath);
                                if (StringUtils.isBlank(result)) {
                                    log.error("result is null===" + advertiser_id + mergeVideoPath);
                                    upload.countDown();
                                    return;
                                }
                                log.info(result);

                                JSONObject jsonObject = null;
                                //上传失败重试
                                try {
                                    jsonObject = JSONObject.parseObject(result);
                                } catch (Exception exception) {
                                    result = uploadAdvideo(String.valueOf(advertiser_id), md5, mergeVideoPath);
                                    if (StringUtils.isBlank(result)) {
                                        log.error("result is null===" + advertiser_id + mergeVideoPath);
                                        upload.countDown();
                                        return;
                                    }
                                    log.info(result);
                                    jsonObject = JSONObject.parseObject(result);
                                }

                                OceanengineUploadFileVideo oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUploadFileVideo.class);
                                if (oceanengineAccount.getCode() == AccountConstant.SUCCESS) {
                                    YlyqMaterialUrl ylyqMaterialUrl = new YlyqMaterialUrl();
                                    ylyqMaterialUrl.setUrl(mergeVideoPath.replace(fileUploadPath, fileDownloadPath));
                                    ylyqMaterialUrl.setMaterialId(oceanengineAccount.getData().getVideo_id());
                                    iYlyqMaterialUrlService.save(ylyqMaterialUrl);
                                    oceanengineUploadFileVideoList.add(oceanengineAccount);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            upload.countDown();
                        }
                    });

                }
                upload.await();
            }


            fixedThreadPool.shutdown();

            log.info("start6");
            return new ResponseData(ResponseData.Result.SUCCESS, oceanengineUploadFileVideoList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseData(ResponseData.Result.FAIL);
    }

}
